package com.hoshiicloud.user.service.impl.usercenter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.user.entity.usercenter.MemberInvoice;
import com.hoshiicloud.user.entity.usercenter.PlatConsumer;
import com.hoshiicloud.user.feign.IdGeneratorService;
import com.hoshiicloud.user.mapper.usercenter.MemberInvoiceMapper;
import com.hoshiicloud.user.service.usercenter.IMemberInvoiceService;
import com.hoshiicloud.user.service.usercenter.IPlatConsumerService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户发票地址Service接口实现类
 *
 * @author : yangcheng
 * @date : 2019/5/13 11:36
 * @mail : maiboyc@163.com
 **/
@Service
public class MemberInvoiceServiceImpl extends ServiceImpl<MemberInvoiceMapper, MemberInvoice> implements IMemberInvoiceService {

    // Id生成Service
    @Autowired
    private IdGeneratorService idGeneratorService;

    // 用户基本信息Service
    @Autowired
    private IPlatConsumerService platMemberService;

    /**
     * 根据id获取
     * @param id ID
     * @return MemberInvoice
     */
    @Cacheable(cacheNames = "memberInvoice", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "用户管理-用户发票地址管理-根据ID查询用户发票地址信息")
    @Override
    public MemberInvoice getById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * 根据一组id
     * @param ids id组
     * @return List<MemberInvoice>
     */
    @Cacheable(cacheNames = "memberInvoice", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#ids")
    @Logable(authName = "用户管理-用户发票地址管理-根据ID组查询用户发票地址信息")
    @Override
    public List<MemberInvoice> getByIds(List<Long> ids) {
        return baseMapper.selectBatchIds(ids);
    }

    /**
     * 保存
     * @param entity 实体对象
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "memberInvoice", allEntries = true)
    @Logable(authName = "用户管理-用户发票地址管理-新增用户发票地址信息")
    @Override
    public Long insert(MemberInvoice entity) throws ServiceException {
        // 调用主键生成微服务生成主键
        String id = idGeneratorService.queryGeneratorId();
        if (id == null) {
            throw new ServiceException(CommonError.error("新增用户发票地址失败,生成ID主键失败"));
        }
        // 调用用户基本信息Service检查用户账户信息是否存在
        PlatConsumer platConsumer = platMemberService.getById(entity.getUserId());
        if (platConsumer == null) {
            throw new ServiceException(CommonError.error("新增用户发票地址失败，没有找到对应的用户基本信息"));
        }
        // 自动生成id，创建日期 修改日期 创建人 修改人 删除标识
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setCreatedBy("admin");// 需要拿当前的登录人
        entity.setUpdatedBy("admin");// 需要拿当前的登录人
        entity.setDeleted(0);
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增用户发票地址失败"));
        }
        return entity.getId();
    }

    /**
     * 修改
     * @param entity 实体对象
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "memberInvoice", allEntries = true)
    @Logable(authName = "用户管理-用户发票地址管理-修改用户发票地址信息")
    @Override
    public Long update(MemberInvoice entity) throws ServiceException {
        // 自动填入修改时间 修改人
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setUpdatedBy("admin1");// 需要拿当前的登录人
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改用户发票地址信息失败"));
        }
        return entity.getId();
    }

    /**
     * 查询
     * @param entity 查询参数实体
     * @return IPage<MemberInvoice>
     */
    @Cacheable(cacheNames = "memberInvoice", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#entity.pageIndex+':'+#entity.pageSize+':'+#entity.userId+':'+#entity.name+':'+#entity.idCard+':'+#entity.phone+':'+#entity.postcode")
    @Logable(authName = "用户管理-用户发票地址管理-分页查询用户发票地址信息")
    @Override
    public IPage<MemberInvoice> List(MemberInvoice entity) {
        QueryWrapper<MemberInvoice> queryWrapper = new QueryWrapper();
        IPage<MemberInvoice> page = new Page();
        if(entity.getPageIndex() != null) {
            page.setCurrent(entity.getPageIndex());
        }
        if(entity.getPageSize() != null){
            page.setSize(entity.getPageSize());
        }
        if (entity.getUserId() != null) {
            queryWrapper.eq("user_id", entity.getUserId());
        }
        if (StringUtils.isNotEmpty(entity.getName())) {
            queryWrapper.like("name", entity.getName());
        }
        if (StringUtils.isNotEmpty(entity.getIdCard())) {
            queryWrapper.like("id_card", entity.getIdCard());
        }
        if (StringUtils.isNotEmpty(entity.getPhone())) {
            queryWrapper.eq("phone", entity.getPhone());
        }
        if (StringUtils.isNotEmpty(entity.getPostcode())) {
            queryWrapper.eq("postcode", entity.getPostcode());
        }
        // 默认查询只查询未逻辑删除的数据
        queryWrapper.eq("deleted", 0);
        return baseMapper.selectPage(page,queryWrapper);
    }

    /**
     * 删除
     * @param id ID
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "memberInvoice", allEntries = true)
    @Logable(authName = "用户管理-用户发票地址管理-删除用户发票地址信息")
    @Override
    public boolean delete(Long id) throws ServiceException {
        MemberInvoice entity = this.getById(id);
        entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除用户发票地址失败"));
        } else {
            return true;
        }
    }

}